import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  // 一级路由
  { path: '/detail/:id', component: () => import('@/views/Detail.vue') },
  { path: '/login', component: () => import('@/views/Login.vue') },
  { path: '/register', component: () => import('@/views/Register.vue') },
  {
    path: '/',
    component: () => import('@/views/Home.vue'),
    children: [
      { path: 'article', component: () => import('@/views/Layout/Article.vue') },
      { path: 'collect', component: () => import('@/views/Layout/Collect.vue') },
      { path: 'like', component: () => import('@/views/Layout/Like.vue') },
      { path: 'user', component: () => import('@/views/Layout/User.vue') }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 导航守卫，判断是否有token，决定能不能通过地址来直接访问
// 可以写成数组形式来
// const allow = ['/login', '/register', '/xxx', '/yyyy']
// if(allow.includes(to.path))
router.beforeEach((to, from, next) => {
  if (to.path === '/login' || to.path === '/register') {
    next()
  } else if (localStorage.getItem('token')) {
    next()
  } else { next('/login') }
})

export default router
